package com.myrslok.util;

import org.apache.commons.io.FileUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.IOException;

public class FileUtil {

    private FileUtil() {
    }

    public static File addRoot(@Nullable final File root, @NotNull final File file) {
        if (root == null) {
            return file;
        }
        return new File(root, file.getPath());
    }

    public static File removeRoot(@Nullable final File root, @NotNull final File file) {
        if (root == null) {
            return file;
        }
        final String parent = file.getParent();
        if (parent == null) {
            return file;
        }
        final String subtractPath = root.getPath();
        if (parent.startsWith(subtractPath)) {
            final String parentPath = parent.substring(subtractPath.length());
            if (parentPath.length() == 0) {
                return new File(file.getName());
            }
            return new File(parentPath.substring(File.separator.length()), file.getName());
        }
        return file;
    }

    /**
     * Create a temp dir by first making a temp file, deleting it and mkdiring() a new *directory*
     * @param prefix .
     * @param suffix .
     * @return .
     */
    @NotNull
    public static File createTempDir(@NotNull final String prefix, @NotNull final String suffix) {
        final File tempFile;
        try {
            tempFile = File.createTempFile(prefix, suffix);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        final boolean deleteSuccessful = tempFile.delete();
        assert deleteSuccessful;
        final boolean mkdirsSuccessful = tempFile.mkdirs();
        assert mkdirsSuccessful;
        return tempFile;
    }

    public static void copyFile(@NotNull final File sourceFile, @NotNull final File targetFile) {
        try {
            // Sorry, java 7 mac not ready for daily use yet
            // Files.copy(sourceFile.toPath(), targetFile.toPath(), StandardCopyOption.COPY_ATTRIBUTES);
            final File targetParent = targetFile.getParentFile();
            if (!targetParent.exists()) {
                final boolean madeDir = targetParent.mkdirs();
                assert madeDir;
            }
            FileUtils.copyFile(sourceFile, targetFile);
            final boolean targetExists = targetFile.exists();
            assert targetExists;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
